package com.shishuo.cms.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.shishuo.cms.dao.ArticleDao;
import com.shishuo.cms.entity.Article;
import com.shishuo.cms.entity.ImageTextEntity;
import com.shishuo.cms.entity.ProductLabelRelEntity;
import com.shishuo.cms.service.ImageTextService;
import com.shishuo.cms.service.ProductLabelRelService;
import com.shishuo.cms.util.MediaUtils;
import com.shishuo.cms.util.ResultFactory;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Component
@Path(value = "/product")
public class ProductAPI extends BaseAPI {
	
	@Autowired
	private ArticleDao articleDao;
	
	@Autowired
	private ProductLabelRelService relService;
	
	@Autowired
	private ImageTextService imageTextService;
	
	
	/**
	 * 保存产品信息
	 * @return
	 * @throws IOException
	 */
	@POST
	@Path("/save")
//	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String save(String json) throws IOException {
		logger.info("开始调用产品新增API, 传入参数为:[ " + json + " ]");
		
		if (StringUtils.isBlank(json)) {
			logger.info("产品新增失败, 参数不能为空");
			return JSON.toJSONString(ResultFactory.createResult("2", "失败, 参数不能为空"));
		}
		
		//Map<String, Object> Map = JSON.parseObject(json, HashMap.class);
		
		Article article = JSON.parseObject(json, Article.class);
		//List<ProductLabelRelEntity> relList = JSON.parseArray(Map.get("label").toString(), ProductLabelRelEntity.class);
		
		logger.info("开始调保存产品...");
		
		articleDao.addArticle(article);
		
		logger.info("开始调保图文信息...");
		
//		if (relList != null && !relList.isEmpty()) {
//			for (ProductLabelRelEntity rel : relList) {
//				rel.setProductId(article.getArticleId());
//				relService.insert(rel);
//			}
//		}
		
		//String imgageTextJson = Map.get("imgageTextJson") == null ? null : Map.get("imgageTextJson").toString();
		
		//saveImageText(article.getArticleId(), imgageTextJson, form);
		
		saveImageText(JSON.parseObject(json).getString("imageText"), article.getArticleId());
		
		logger.info("新增产品成功");
		
		return JSON.toJSONString(ResultFactory.createResult("1", "成功"));
	}
	
	@POST
	@Path("/update")
	public String update(String json) {
		logger.info("开始调用产品修改API, 传入参数为:[ " + json + " ]");
		
		if (StringUtils.isBlank(json)) {
			return JSON.toJSONString(ResultFactory.createResult("2", "失败, 参数不能为空"));
		}
		
		Article article = JSON.parseObject(json, Article.class);
		List<ProductLabelRelEntity> relList = JSON.parseArray(json, ProductLabelRelEntity.class);
		
		if (article.getArticleId() == 0) {
			logger.info("产品修改失败, 产品ID不能为空");
			return JSON.toJSONString(ResultFactory.createResult("2", "失败, 产品ID不能为空"));
		}
		
		articleDao.updateArticle(article);
		
//		Example example = new Example(ProductLabelRelEntity.class);
//		Criteria criteria = example.createCriteria();
//		
//		criteria.andEqualTo("productId", article.getArticleId());
//		
//		relService.deleteByExample(example);
		
//		if (relList != null && !relList.isEmpty()) {
//			for (ProductLabelRelEntity rel : relList) {
//				rel.setProductId(article.getArticleId());
//				relService.insert(rel);
//			}
//		}
		
		Example example = new Example(ImageTextEntity.class);
		Criteria criteria = example.createCriteria();
		
		criteria.andEqualTo("productId", article.getArticleId());
		
		imageTextService.deleteByExample(example);
		
		saveImageText(JSON.parseObject(json).getString("imageText"), article.getArticleId());
		
		logger.info("产品修改成功");
		
		return JSON.toJSONString(ResultFactory.createResult("1", "成功"));
	}
	
	public boolean saveImageText(String json, long productId) {
		
		List<ImageTextEntity> entity = JSON.parseArray(json, ImageTextEntity.class);
		
		if (entity != null && !entity.isEmpty()) {
			for (ImageTextEntity imageTextEntity : entity) {
				imageTextEntity.setProductId(productId);
				imageTextService.insert(imageTextEntity);
			}
		}
		
		return true;
	}
	
	@GET
	@Path("/getProductInfo/{productId}")
	public String getProductInfo(@PathParam("productId") Long productId) throws Exception {
		
		logger.info("调用获取产品信息API, 传入参数为:[ " + productId + " ]");
		
		if (productId == null) {
			logger.info("获取产品信息失败, 产品ID不能为空");
			return JSON.toJSONString(ResultFactory.createResult("2", "失败, 产品ID不能为空"));
		}
		
		Article article = articleDao.getArticleById(productId);
		
		if (article == null) {
			logger.info("获取产品信息失败, 未查询到产品信息");
			return JSON.toJSONString(ResultFactory.createResult("2", "失败, 未查询到产品信息"));
		}
		
//		List<ProductLabelRelEntity> relList = relService.getListByFieldEqual("productId", article.getArticleId());
		
		List<ImageTextEntity> imageTextEntities = imageTextService.getListByFieldEqual("productId", productId);
		
		@SuppressWarnings("unchecked")
		Map<String, Object> resultMap = JSON.parseObject(JSON.toJSONString(article), HashMap.class);;
		resultMap.put("imageText", imageTextEntities);
		
		return JSON.toJSONString(resultMap);
	}

	/*private Map<String, Object> saveImageText(long productId, String imgageTextJson, FormDataMultiPart form) throws IOException {
		
		logger.info("开始获取表单图文内容...");
		
		@SuppressWarnings("unchecked")
		Map<String, Object> map = JSON.parseObject(imgageTextJson, HashMap.class);
		
		List<FormDataBodyPart> l = form.getFields("file");

		for (FormDataBodyPart p : l) {
			InputStream is = p.getValueAs(InputStream.class);
			FormDataContentDisposition detail = p.getFormDataContentDisposition();

			String filePath = MediaUtils.saveImage(is, 100, 100);
			
			String fieldName = detail.getName();
			
			String imgageText = map.get("ImageText" + fieldName) == null ? null
					: map.get("ImageText" + fieldName).toString();

			ImageTextEntity entity = new ImageTextEntity();
			entity.setDesc(imgageText);
			entity.setProductId(productId);
			entity.setImageUrl(filePath);
			
			imageTextService.insert(entity);
		}
		
		return null;
	}*/
	
	@POST
	@Path("/uploadImage")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String uploadImage(FormDataMultiPart form) throws IOException {

		List<FormDataBodyPart> l = form.getFields("file");

		List<String> filePathList = new ArrayList<String>();
		
		for (FormDataBodyPart p : l) {
			filePathList.add(MediaUtils.saveImage(p, 100, 100));
		}

		return JSON.toJSONString(filePathList);
	}
	
	
}
